#!/usr/bin/env python
import os
import subprocess
from sys import executable as PYTHON_BIN

from distutils.core import setup
from distutils.command.build_py import build_py as _build_py
from distutils.command.install_data import install_data as _install_data

from searxqt.version import __version__

ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
LOCALES_PATH = os.path.join(ROOT_PATH, 'locale')
THEMES_PATH = os.path.join(ROOT_PATH, 'themes')
DOCS_PATH = os.path.join(ROOT_PATH, 'docs')
SCHEMA_PATH = os.path.join(ROOT_PATH, 'data/schema')


def compileLocales():
    """ Compiles all found locales .po to .mo files.
    """
    cmd = os.path.join(ROOT_PATH, 'utils', 'locale_tool.sh')
    cmd += " -m all"
    if os.system(cmd) != 0:
        print("Failed to compile locales.")
        return False
    return True


def genMoList():
    """ Returns the 'data_files' for all found .mo files.
    """
    data_files = []
    for langDir in os.listdir(LOCALES_PATH):
        path = os.path.join(LOCALES_PATH, langDir)

        if not os.path.isdir(path):
            continue

        moPath = os.path.join(path, "LC_MESSAGES", "searx-qt.mo")

        if not os.path.exists(moPath):
            continue

        targetPath = os.path.join("share/locale", langDir, "LC_MESSAGES")

        data_files.append(
            (targetPath, [moPath])
        )

    return data_files


def makeThemes():
    """ Compiles the resource files for all themes. (.qrc to .rcc)
    """
    cmd = f'{PYTHON_BIN} utils/themes_tool.py make all'
    if os.system(cmd) != 0:
        print("Failed to make all themes.")
        return False
    return True


def themeDataFiles():
    """ Returns the 'data_files' for all found theme files.
    """
    cmd = f'{PYTHON_BIN} ./utils/themes_tool.py list'
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    stdout, err = proc.communicate()

    if proc.returncode != 0:
        print('Failed to list themes.')
        sys.exit(1)

    data_files = []
    for key in stdout.decode().split('\n'):
        if not key:
            continue

        cmd = f'{PYTHON_BIN} ./utils/themes_tool.py files {key}'
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
        stdout, err = proc.communicate()

        if proc.returncode != 0:
            print(
                'Failed to get file list for theme with key \'{0}\''
                .format(key)
            )
            continue

        files = []
        for filepath in stdout.decode().split('\n'):
            if not filepath:
                continue
            files.append(filepath)

        data_files.append(
            (os.path.join("share/searx-qt/themes", key), files)
        )

    return data_files


def docFiles():
    """ Returns the 'data_files' for docs excluding images.
    """
    return ['COPYING', 'README.md', 'CHANGELOG.md',
            'docs/index.rst', 'docs/index.html', 'docs/style.css']

def docImages():
    """ Returns the 'data_files' for doc images.
    """
    data_files = []
    imgPath = os.path.join(DOCS_PATH, "images/")
    for entry in os.listdir(imgPath):
        path = os.path.join(imgPath, entry)

        if not os.path.isfile(path):
            continue

        data_files.append(path)

    return data_files


def schemaFiles():
    """ Returns the 'data_files' for json schemas
    """
    return ['data/schema/searxng_config.json',
            'data/schema/searxng_query.json',
            'data/schema/searx_space_instances.json']


class build_py(_build_py):
    def run(self):
        if not compileLocales():
            return None
        if not makeThemes():
            return None
        return _build_py.run(self)


class install_data(_install_data):
    def run(self):
        if os.path.exists(LOCALES_PATH):
            self.data_files += genMoList()
        if os.path.exists(THEMES_PATH):
            self.data_files += themeDataFiles()
        return _install_data.run(self)


setup(name='searx-qt',
      version=__version__,
      license='GPLv3',
      description=('Lightweight desktop application for Searx.'),
      author='CYBERDEViL',
      url='https://notabug.org/cyberdevil',
      packages=[
        'searxqt',
        'searxqt.widgets',
        'searxqt.models',
        'searxqt.views',
        'searxqt.core',
        'searxqt.utils'
      ],
      classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: X11 Applications :: Qt',
        'Topic :: Internet',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Internet :: WWW/HTTP'
      ],
      scripts=[
        'bin/searx-qt'
      ],
      data_files=[
        ('share/applications', ['share/searx-qt.desktop']),
        ('share/doc/searx-qt', docFiles()),
        ('share/doc/searx-qt/images', docImages()),
        ('share/searx-qt/schema', schemaFiles())
      ],
      cmdclass={
        'build_py': build_py,
        'install_data': install_data
      })
